package mbp.logger;

import jade.core.AID;
import jade.core.Agent;
import jade.lang.acl.ACLMessage;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import pl.edu.agh.logview.webservice.MessageBean;
import pl.edu.agh.logview.webservice.MessageBeanImpl;

public class LoggerProxy {

	private static final String RECEIVE = "ODEBRANIE";
	private static final String STATE = "STAN";
	private static final String SEND = "WYSLANIE";

	private static BlockingQueue<MessageBean> loggerQueue = new LinkedBlockingQueue<MessageBean>();
	private static LoggerThread logger = null;

	private static Date getTime() {
		Calendar cal = Calendar.getInstance();
		return cal.getTime();
	}

	public static MessageBean takeMessage() throws InterruptedException {
		return loggerQueue.take();
	}

	public static void logReceiving(ACLMessage message, Agent agent) {
		if (logger == null) {
			logger = new LoggerThread();
			logger.start();
		}
		String sender = message.getSender().getName();
		String receiver = agent.getName();
		String content = message.getContent();

		// printToConsole(RECEIVE, sender, receiver, content);
		loggerQueue.add(new MessageBeanImpl(RECEIVE, content, getTime(),
				sender, receiver));

	}

	public static void logStateChange(String newState, Agent agent) {
		if (logger == null) {
			logger = new LoggerThread();
			logger.start();
		}
		String agentName = agent.getName();
		// printToConsole(agentName, newState);
		loggerQueue.add(new MessageBeanImpl(STATE, newState, getTime(),
				agentName, null));

	}

	public static void logSending(ACLMessage message, Agent agent) {
		if (logger == null) {
			logger = new LoggerThread();
			logger.start();
		}
		String sender = agent.getAID().getName();
		String receiver = ((AID) (message.getAllIntendedReceiver().next()))
				.getName();
		String content = message.getContent();

		// printToConsole(SEND, sender, receiver, content);
		loggerQueue.add(new MessageBeanImpl(SEND, content, getTime(), sender,
				receiver));

	}
	
}
